package Thread;

import java.util.concurrent.locks.ReentrantLock;

public class Demo42 {
    private static int counter = 0;
    public static void main(String[] args) throws InterruptedException {
        //trylock(超时时间):加锁,如果获取不到锁,等待⼀定的时间之后就放弃加锁
        ReentrantLock locker = new ReentrantLock(true);
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                locker.lock();
                counter++;
                locker.unlock();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                locker.lock();
                counter++;
                locker.unlock();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter);
        // •
        //锁竞争不激烈的时候,使⽤synchronized,效率更⾼,⾃动释放更⽅便.
        // •
        //锁竞争激烈的时候,使⽤ReentrantLock,搭配trylock更灵活控制加锁的⾏为,⽽不是死等.
        // •
        //如果需要使⽤公平锁,使⽤ReentrantLock
    }
}
